package model

type DrawServer interface {
	Create(draw *DrawList) (err error)
	GetCount(userId int) int
	GetCount3(userId int) int
	Check(int) int
	GetSumAllTime(createdAt int) (int, error)
	GetSumDayTime(openId string, createdAt int) (sum int, err error)
	GetCountToday(userId, createdAt int) (count int)
}

type drawListServer struct {
}

func NewDrawServer() DrawServer {
	return &drawListServer{}
}

func (u *drawListServer) Create(draw *DrawList) (err error) {
	sql := "INSERT INTO draw_list (open_id, money, create_time, created_day, sign, name) VALUES (?, ?, ?, ?, ?, ?)"
	stmt, err := Db.Prepare(sql)
	if err != nil {
		return
	}
	defer stmt.Close()

	res, err := stmt.Exec(draw.OpenId, draw.Money, draw.CreateTime, draw.CreatedDay, draw.Sign, draw.Name)
	if err != nil {
		return
	}
	id, err := res.LastInsertId()
	if err != nil {
		return
	}
	draw.Id = int(id)
	return nil
}

func (u *drawListServer) GetCount(userId int) (count int) {
	_ = Db.QueryRow("SELECT count(id) FROM draw_list WHERE user_id = ?", userId).Scan(&count)
	return
}

func (u *drawListServer) GetCount3(userId int) (count int) {
	_ = Db.QueryRow("SELECT count(id) FROM draw_list WHERE user_id = ? AND money = 30 AND types = 1", userId).Scan(&count)
	return
}

func (u *drawListServer) Check(userId int) (count int) {
	_ = Db.QueryRow("SELECT count(id) FROM draw_list WHERE types = 1 AND user_id = ?", userId).Scan(&count)
	return
}

func (u *drawListServer) GetSumAllTime(createdAt int) (sum int, err error) {
	err = Db.QueryRow("SELECT sum(money) FROM draw_list WHERE created_day = ?", createdAt).Scan(&sum)
	return
}

func (u *drawListServer) GetSumDayTime(openId string, createdAt int) (sum int, err error) {
	err = Db.QueryRow("SELECT sum(money) FROM draw_list WHERE created_day = ? AND open_id = ?", createdAt).Scan(&sum)
	return
}

func (u *drawListServer) GetCountToday(userId, createdAt int) (count int) {
	_ = Db.QueryRow("SELECT count(id) FROM draw_list WHERE types = 1 AND user_id = ? AND created_day = ?", userId, createdAt).Scan(&count)
	return
}
